package com.sky.utils;

import java.util.Map;

/**
 * 经纬度距离计算
 *
 * @author moningxi
 */
public class GeoDistinctUtil {
    private static final double R = 6371; // 地球半径，单位：千米

    public static double calculateDistance(Map<String, Double> map1, Map<String, Double> map2) {
        Double lon1 = map1.get("lng");
        Double lat1 = map1.get("lat");
        Double lon2 = map2.get("lng");
        Double lat2 = map2.get("lat");
        // 将经纬度转换为弧度
        double lat1Rad = Math.toRadians(lat1);
        double lon1Rad = Math.toRadians(lon1);
        double lat2Rad = Math.toRadians(lat2);
        double lon2Rad = Math.toRadians(lon2);

        // 计算经纬度差值
        double deltaLat = lat2Rad - lat1Rad;
        double deltaLon = lon2Rad - lon1Rad;

        // 计算a的值
        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
                Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                        Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);

        // 计算c的值
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        // 计算最终的距离，单位：千米
        return R * c;
    }
}
